import { Service } from 'egg';
import { Op } from 'sequelize';
// 菜单增删改查
export default class MenuService extends Service {
  async getMenuList() {
    const { ctx } = this;
    const menuList = await ctx.model.Menu.findAll();
    return menuList;
  }
  async getMenuListByRoleId(roleId) {
    const { ctx } = this;
    const menuList = await ctx.model.Menu.findAll({
      where: {
        id: {
          [Op.in]: await ctx.model.RoleMenu.findAll({
            where: {
              roleId,
            },
          }).then(res => {
            return res.map(item => {
              return item.menuId;
            });
          }),
        },
      },
      order: [[ 'sort', 'ASC' ]],
    });
    return menuList;
  }
  async getMenuListByUserId(userId) {
    const { ctx } = this;
    const menuList = await ctx.model.Menu.findAll({
      where: {
        id: {
          [Op.in]: await ctx.model.RoleMenu.findAll({
            where: {
              userId,
            },
          }).then(res => {
            return res.map(item => {
              return item.menuId;
            });
          }),
        },
      },
      order: [[ 'sort', 'ASC' ]],
    });
    return menuList;
  }
  async addMenu(menu) {
    const { ctx } = this;
    const menuList = await ctx.model.Menu.create(menu);
    return menuList;
  }
  async updateMenu(menu) {
    const { ctx } = this;


    const menuList = await ctx.model.Menu.update(menu, {
      where: {
        id: menu.id,
      },
    });

    return menuList;
  }
  async deleteMenu(menu) {
    const { ctx } = this;
    const menuList = await ctx.model.Menu.destroy({
      where: {
        id: menu.id,
      },
    });
    return menuList;
  }
}

